const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

function parseBackupFile(filePath) {
    const sql = fs.readFileSync(filePath, 'utf8');
    const lines = sql.split(/\r?\n/);
    const items = [];
    const insertPrefix = "INSERT INTO `level_experience`";
    const valuesRegex = /VALUES\s*\(([^)]+)\)/i;
    for (const line of lines) {
        if (!line.startsWith(insertPrefix)) continue;
        const m = line.match(valuesRegex);
        if (!m) continue;
        const valuesPart = m[1];
        // 拆出前两项: level, experience
        const parts = valuesPart.split(',').map(s => s.trim());
        if (parts.length < 2) continue;
        const level = parseInt(parts[0], 10);
        const experience = parseInt(parts[1], 10);
        if (!Number.isNaN(level) && !Number.isNaN(experience)) {
            items.push({ level, experience });
        }
    }
    return items;
}

async function main() {
    const args = process.argv.slice(2);
    const getArg = (name, def) => {
        const i = args.indexOf(name);
        return i >= 0 && args[i + 1] ? args[i + 1] : def;
    };

    const fileArg = getArg('--file', '');
    if (!fileArg) {
        console.error('用法: node scripts/restore-level-experience-from-sql.js --file /absolute/path/to/backup.sql');
        process.exit(1);
    }
    const filePath = path.isAbsolute(fileArg) ? fileArg : path.resolve(process.cwd(), fileArg);
    if (!fs.existsSync(filePath)) {
        console.error('找不到备份文件:', filePath);
        process.exit(1);
    }

    const pairs = parseBackupFile(filePath);
    if (pairs.length === 0) {
        console.error('未能从备份中解析到任何 level/experience 记录');
        process.exit(1);
    }

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        multipleStatements: true,
        timezone: '+08:00'
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        await conn.beginTransaction();

        let updated = 0, inserted = 0;
        for (const { level, experience } of pairs) {
            const [res] = await conn.execute('UPDATE level_experience SET experience = ?, updated_at = NOW() WHERE level = ?', [experience, level]);
            if ((res && res.affectedRows) > 0) {
                updated += 1;
            } else {
                // 插入（standard_exp_per_fight 留空）
                await conn.execute('INSERT INTO level_experience (level, experience, standard_exp_per_fight, created_at, updated_at) VALUES (?, ?, NULL, NOW(), NOW())', [level, experience]);
                inserted += 1;
            }
        }

        await conn.commit();
        console.log(`恢复完成: 更新 ${updated} 行, 新增 ${inserted} 行 (共 ${pairs.length})`);
    } catch (e) {
        if (conn) await conn.rollback().catch(() => { });
        console.error('恢复失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch((e) => {
    console.error(e);
    process.exit(1);
});
